package com.itheima;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.jupiter.api.Test;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtTest {
    @Test
    public void testGen(){
        Map<String, Object> claims = new HashMap<>();
        claims.put("id",1);
        claims.put("username","admin");
        String token = JWT.create()
                .withClaim("user",claims)
                .withExpiresAt(new Date(System.currentTimeMillis()+1000*60*60*12)) //设置过期时间
                .sign(Algorithm.HMAC256("itheima"));  //指定算法，配置密钥

        System.out.println(token);
    }

    @Test
    public void testParse()  {
        // 定义字符串，模拟从请求头中获取token
        String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" +
                ".eyJ1c2VyIjp7ImlkIjoxLCJ1c2VybmFtZSI6ImFkbWluIn0sImV4cCI6MTczNjAxMjU1N30" +
                ".m9w0qpIs8G3nZubi_DE6WtUIRsuawM1TpCOiAYhMGtw";

        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("itheima"))
                    .build();
            DecodedJWT decodedJWT = jwtVerifier.verify(token); // 验证token，生成一个解析后的JWT对象
            Claim userClaim = decodedJWT.getClaim("user");
            if (userClaim.asMap() != null) {
                System.out.println(userClaim);
            } else {
                System.out.println("User claim is not present or not a map.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //如果修改了密钥，头部和载荷的值，验证就会失败
        //token过期，验证就会失败

    }
}
